﻿using System;
using System.Web.Caching;

namespace ECommon
{
    /// <summary>
    /// 缓存工具类
    /// </summary>
    public static partial class CacheTool
    {
        /// <summary>
        /// 根据键值设置缓存
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="value">缓存值</param>
        /// <param name="expireMinutes">过期分钟数</param>
        public static void Set(string key, object value, int? expireMinutes = null)
        {
            if (expireMinutes == null || expireMinutes.Value <= 0)
            {
                _cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            }
            else
            {
                _cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(expireMinutes.Value));
            }
        }

        /// <summary>
        /// 缓存实例
        /// </summary>
        private static Cache _cache = new Cache();

        /// <summary>
        /// 根据键值获取缓存
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns>缓存</returns>
        public static object Get(string key)
        {
            return _cache.Get(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T">引用类型</typeparam>
        /// <param name="key">缓存键值</param>
        /// <returns>缓存值</returns>
        /// <exception cref="ArgumentException">变量错误异常</exception>
        public static T Get<T>(string key)
        {
            object objTmp = _cache.Get(key);
            if (objTmp == null)
            {
                throw new ArgumentException("变量转换过程中参数错误");
            }
            return (T)objTmp;
        }

        /// <summary>
        /// 根据键值移除缓存
        /// </summary>
        /// <param name="key">缓存键值</param>
        public static void Remove(string key)
        {
            _cache.Remove(key);
        }
    }
}